package com.aurora.leetcode.answer;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : Aurora
 * @date : 2024/5/16 09:21
 * @description
 * <p>给你两个字符串：ransomNote 和 magazine ，判断 ransomNote 能不能由 magazine 里面的字符构成。
 * 如果可以，返回 true ；否则返回 false 。
 * magazine 中的每个字符只能在 ransomNote 中使用一次。</p>
 * <p>example1</p>
 * <p>输入：ransomNote = "a", magazine = "b"</p>
 * <p>输出：false</p>
 * <p>example2</p>
 * <p>输入：ransomNote = "aa", magazine = "ab"</p>
 * <p>输出：false</p>
 * <p>example3</p>
 * <p>输入：ransomNote = "aa", magazine = "aab"</p>
 * <p>输出：true</p>
 */
public class CanConstruct_383 {

    //方法一：map
    public boolean canConstruct(String ransomNote, String magazine) {
        Map<Character,Integer> map = new HashMap<>();
        for(int i=0; i<magazine.length(); ++i){
            char c = magazine.charAt(i);
            map.merge(c,1,Integer::sum);
        }
        for(int i=0; i<ransomNote.length(); ++i){
            char c = ransomNote.charAt(i);
            Integer num = map.get(c);
            if(num == null || num == 0) return false;
            map.merge(c, -1, Integer::sum);
        }
        return true;
    }
    //方法二：数组
    public boolean canConstruct2(String ransomNote, String magazine) {
        if(magazine.length() < ransomNote.length()) return false;
        int[] arr = new int[26];
        for(int i=0; i<magazine.length(); ++i){
            int num2 = magazine.charAt(i)-97;
            if(i < ransomNote.length()){
                int num1 = ransomNote.charAt(i)-97;
                arr[num1] -= 1;
            }
            arr[num2] += 1;
        }
        for(int i=0; i<arr.length; ++i){
            if(arr[i] < 0)return false;
        }
        return true;
    }

    public static void main(String[] args) {
        CanConstruct_383 obj = new CanConstruct_383();
//        System.out.println(obj.canConstruct("aa", "b"));
        System.out.println(obj.canConstruct2("aa", "aab"));
    }
}
